package com.order.service;

import com.order.dto.RegisterRequest;
import com.order.entity.SysUser;
import com.order.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * 认证服务
 */
@Service
public class AuthService {

    @Autowired
    private SysUserMapper sysUserMapper;

    private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    /**
     * 用户登录
     */
    public SysUser login(String username, String password) {
        SysUser user = sysUserMapper.findByUsername(username);
        if (user != null && passwordEncoder.matches(password, user.getPassword())) {
            return user;
        }
        return null;
    }

    /**
     * 用户注册
     */
    public void register(RegisterRequest request) {
        // 检查用户名是否已存在
        if (sysUserMapper.findByUsername(request.getUsername()) != null) {
            throw new RuntimeException("用户名已存在");
        }

        // 检查角色类型是否有效（只允许注册用户和技术员）
        if (request.getRoleType() != 3 && request.getRoleType() != 4) {
            throw new RuntimeException("无效的角色类型");
        }

        // 创建新用户
        SysUser user = new SysUser();
        user.setUsername(request.getUsername());
        user.setPassword(passwordEncoder.encode(request.getPassword()));
        user.setRealName(request.getRealName());
        user.setPhone(request.getPhone());
        user.setRoleType(request.getRoleType());
        user.setStatus(1);

        sysUserMapper.insert(user);
    }

    /**
     * 根据ID获取用户
     */
    public SysUser getUserById(Long id) {
        return sysUserMapper.findById(id);
    }

    /**
     * 根据用户名获取用户
     */
    public SysUser getUserByUsername(String username) {
        return sysUserMapper.findByUsername(username);
    }
}